package day13.demo;

import day13.exercise.Product;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ProductDaoImpl implements IProductDao{
   public static final String PATH="src/test/demo/product.txt";
    @Override
    public List<Product> findAll() {
        ObjectInputStream in=null;
        List<Product> products=null;
        try {
            in=new ObjectInputStream(new FileInputStream(PATH));
            try {
                products= (List<Product>) in.readObject();
            } catch (ClassNotFoundException e) {
               // e.printStackTrace();
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(null!=in){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return products;
    }

    @Override
    public void save(Product product) {
        ObjectOutputStream out=null;
        List<Product> products=findAll();
        try {
            out=new ObjectOutputStream(new FileOutputStream(PATH));
            if(null==products)
                products=new ArrayList<>();
            products.add(product);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(null!=out){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    @Override
    public void delByrand(String brand) {
        List<Product>products=findAll();
        if (products!=null) {
            Iterator<Product> iterator = products.iterator();
            while (iterator.hasNext()) {
                Product p = iterator.next();
                if (p.getBrand().equals(brand)) {
                    iterator.remove();
                }
            }
            ObjectOutputStream out = null;
            try {
                out = new ObjectOutputStream(new FileOutputStream(PATH));
                for (Product p : products) {
                    save(p);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (null != out) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }
}
